﻿#if !(UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_WIN || STEAMWORKS_LIN_OSX)
#define DISABLESTEAMWORKS
#else
using Steamworks;
#endif

using System;
using System.Net;
using Mirror;
using Mirror.Discovery;
using UnityEngine;
using UnityEngine.Events;



/*
	Discovery Guide: https://mirror-networking.com/docs/Guides/NetworkDiscovery.html
    Documentation: https://mirror-networking.com/docs/Components/NetworkDiscovery.html
    API Reference: https://mirror-networking.com/docs/api/Mirror.Discovery.NetworkDiscovery.html
*/

public class DiscoveryRequest : NetworkMessage
{
}

public class DiscoveryResponse : NetworkMessage
{
    public int serverId;
    public string host;
    public string name;
    public int numPlayers=0;
    public int numPlayersMax = 0;
    public bool isPlaying = false;
    public ulong steamId=0;
    public Uri uri;
}


public class RoomListFindout : NetworkDiscoveryBase<DiscoveryRequest, DiscoveryResponse>
{

    public int ServerId { get; private set; }
    public Transport transport;
    public DiscoveryResponseCallback OnServerFound = new DiscoveryResponseCallback();
    public string roomName="233";
    public bool isPlaying = false;

    public override void Start()
    {

        ServerId = UnityEngine.Random.Range(int.MinValue, int.MaxValue);
        if (transport == null)
            transport = Transport.activeTransport;

        base.Start();
    }
    #region Server

    /// <summary>
    /// Reply to the client to inform it of this server
    /// </summary>
    /// <remarks>
    /// Override if you wish to ignore server requests based on
    /// custom criteria such as language, full server game mode or difficulty
    /// </remarks>
    /// <param name="request">Request coming from client</param>
    /// <param name="endpoint">Address of the client that sent the request</param>
    protected override void ProcessClientRequest(DiscoveryRequest request, IPEndPoint endpoint)
    {
        base.ProcessClientRequest(request, endpoint);
    }

    /// <summary>
    /// Process the request from a client
    /// </summary>
    /// <remarks>
    /// Override if you wish to provide more information to the clients
    /// such as the name of the host player
    /// </remarks>
    /// <param name="request">Request coming from client</param>
    /// <param name="endpoint">Address of the client that sent the request</param>
    /// <returns>A message containing information about this server</returns>
    protected override DiscoveryResponse ProcessRequest(DiscoveryRequest request, IPEndPoint endpoint)
    {
        Debug.Log("send host : " + transport.ServerUri().Host);
        try
        {
            // this is an example reply message,  return your own
            // to include whatever is relevant for your game
            return new DiscoveryResponse
            {
                serverId = ServerId,
                name = roomName,
                numPlayers = OnlineManager.singleton.numPlayers,
                numPlayersMax = OnlineManager.singleton.maxConnections,
                host = transport.ServerUri().Host,
                uri = transport.ServerUri(),
                isPlaying = isPlaying,

            };
            
        }
        catch (NotImplementedException)
        {
            Debug.LogError($"Transport {transport} does not support network discovery");
            throw;
        }
    }

    #endregion

    #region Client

    /// <summary>
    /// Create a message that will be broadcasted on the network to discover servers
    /// </summary>
    /// <remarks>
    /// Override if you wish to include additional data in the discovery message
    /// such as desired game mode, language, difficulty, etc... </remarks>
    /// <returns>An instance of ServerRequest with data to be broadcasted</returns>
    protected override DiscoveryRequest GetRequest()
    {
        return new DiscoveryRequest();
    }

    /// <summary>
    /// Process the answer from a server
    /// </summary>
    /// <remarks>
    /// A client receives a reply from a server, this method processes the
    /// reply and raises an event
    /// </remarks>
    /// <param name="response">Response that came from the server</param>
    /// <param name="endpoint">Address of the server that replied</param>
    protected override void ProcessResponse(DiscoveryResponse response, IPEndPoint endpoint) 
    {
        UriBuilder realUri = new UriBuilder(response.uri)
        {
            Host = endpoint.Address.ToString(),
        };
        response.uri = realUri.Uri;
        response.host = realUri.Uri.Host;
        OnServerFound.Invoke(response);
    }

    #endregion
}
